package com.tom.config;

import org.elasticsearch.Build;
import org.elasticsearch.index.query.QueryBuilder;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static com.tom.constants.MQConstants.*;


//rabbitMQ的配置
@Configuration
public class RabbitMQConfig {


    // 创建交换机
    @Bean(EXCHANGE_NAME_TOPIC)
    public Exchange exchangeNamwTopic(){
        return ExchangeBuilder.topicExchange(EXCHANGE_NAME_TOPIC).durable(true).build();
    }

    // 创建队列,email
    @Bean(QUEUE_NAME_EMAIL)
    public Queue queueNameEmail(){
        return new Queue(QUEUE_NAME_EMAIL,true);
    }
    // 创建队列,sms
    @Bean(QUEUE_NAME_SMS)
    public Queue queueNameSMS(){
        return new Queue(QUEUE_NAME_SMS,true);
    }
    // 创建队列,message
    @Bean(QUEUE_NAME_SYSTEM_MESSAGE)
    public Queue queueNameMessage(){
        return new Queue(QUEUE_NAME_SYSTEM_MESSAGE,true);
    }

    // 队列绑定交换机
    @Bean
    public Binding queueEmailBinding(){
        // noargs没有别的参数
        return BindingBuilder.bind(queueNameEmail()).to(exchangeNamwTopic()).with("#.email").noargs();
    }
    // 队列绑定交换机
    @Bean
    public Binding queueSMSBinding(){
        // noargs没有别的参数
        return BindingBuilder.bind(queueNameSMS()).to(exchangeNamwTopic()).with("#.sms").noargs();
    }
    // 队列绑定交换机
    @Bean
    public Binding queueMessageBinding(){
        // noargs没有别的参数
        return BindingBuilder.bind(queueNameMessage()).to(exchangeNamwTopic()).with("#.message").noargs();
    }

    //定义RabbitTemplate 指定 JSON转换器
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        //1.把要发送的消息内容 ，交换机，rontkey等都保存下来到Mysql
        //2.后续可以用来重写发送消息，甚至可以使用一个定时任务不停的重试，可以甚至一个最大重试次数
        //设置消息回调
        rabbitTemplate.setMandatory(true);

        return rabbitTemplate;
    }
}